<?php
/*
* 数据库操作日志模型
* 龙啸轩内容管理系统V3 20200506
*/

namespace model;

class log_sql
{

    public function insertData($dothing)
    {
        $pdo = \z\pdo::Init();
        $prefix = $pdo->GetConfig();
        $fix = $prefix['prefix'];

        $data = [
            'username' => sessionInfo('username'),
            'loginip' => sessionInfo('loginip'),
            'ca' => ROUTE['ctrl'] . '/' . ROUTE['act'],
            'useragent' => $_SERVER['HTTP_USER_AGENT'], //用户浏览器信息
            'time' => date('Y-m-d H:i:s', time()),
            'dothing' => $dothing,
        ];

        //只保留5000条数据
        $sql = "SELECT COUNT(*) as totle from {$fix}log_sql";;
        $count  = $pdo->QueryOne($sql);
        if ($count['totle'] > 4999) {
            $sqldel = "DELETE from {$fix}log_sql order by id asc LIMIT 1";
            $pdo->Submit($sqldel);
        }

        //写入数据库
        $sqlInsert = "INSERT INTO {$fix}log_sql (username, ca, loginip, useragent, time, dothing) VALUES ('{$data["username"]}', '{$data["ca"]}', '{$data["loginip"]}', '{$data["useragent"]}', '{$data["time"]}', '{$data["dothing"]}')";

        $pdo->Submit($sqlInsert);
    }

    //获取数据并分页
    public function jsonPageSelect()
    {
        $db = \ext\db::Init('log_sql');
        $p = intval($_GET['page'] ?? 0) ?: 1;
        $num = intval($_GET['limit'] ?? 0) ?: 15;
        $page = ['num' => $num, 'p' => $p, 'return' => true];

        if (isset($_GET['username'])) {
            $where['username LIKE'] = '%' . $_GET['username'] . '%';
            $result['data'] = $db->where($where)->Page($page)->order('id DESC')->select();
            $result['page'] = $db->getPage();
        } else {
            $result['data'] = $db->Page($page)->order('id DESC')->select();
            $result['page'] = $db->getPage();
        }
        return $result;
    }
}
